package com.mymvc.exception;

import com.sun.jmx.snmp.SnmpUnknownModelLcdException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassName: MyExceptionResolver
 * Package: com.mymvc.exception
 * Description:
 *
 * @Author 刘英杰
 * @Create 2025/2/10 10:16
 * @Version 1.0
 */

@Component
public class MyExceptionResolver implements HandlerExceptionResolver {
    /**
     * 一旦项目中出现异常都会调用解析器resolveException方法
     * @param request
     * @param response
     * @param handler:抛出异常的handler对象(Controller对象)
     * @param ex:接收到抛出的异常对象
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        //将错误信息记录到日志文件
        Logger fileLogger = LogManager.getLogger("fileLogger");
        fileLogger.error(handler+":"+ex.getMessage(),ex);//将异常的追踪信息写入

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error");
        modelAndView.addObject("msg","访问出错");
        return modelAndView;
    }
}
